package com.tongsys.server.controller;

import com.tongsys.server.entity.Permission;
import com.tongsys.server.entity.User;
import com.tongsys.server.service.ILoginService;
import com.tongsys.server.utils.MenuUtils;
import com.tongsys.server.utils.RtnUtils;
import com.tongsys.server.vo.UserVo;
import io.swagger.annotations.ApiOperation;
import net.bytebuddy.utility.privilege.GetSystemPropertyAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api")
public class LoginController {

    @Resource
    private ILoginService iLoginService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @ApiOperation("登录")
    @PostMapping("/login")
    public RtnUtils login(@RequestBody User user){
        //获取初始密码，填入数据库中
       /* String encode = bCryptPasswordEncoder.encode("123456");
        System.out.println(encode);*/
        RtnUtils login = iLoginService.login(user);
        return login;
    }

    @ApiOperation("获取用户登录信息")
    @PostMapping("/getInfo")
    public RtnUtils getLoginInfo(){
        //从上下文中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user=null;
        if(authentication==null){
            return RtnUtils.err().msg("查询用户信息失败");
        }
        //获取用户信息
        user=(User) authentication.getPrincipal();
        //获取用户权限
        List<String> permissionList = user.getPermissionList();

        Object[] roles=permissionList.stream()
                .filter(item->item!=null)
                .toArray();
        //返回用户信息
        UserVo userVo = new UserVo(user.getId(), user.getUsername(), user.getAvatar(), "", roles);

        return RtnUtils.ok().data(userVo).msg("获取用户信息成功");
    }

    @ApiOperation("获取菜单信息")
    @PostMapping("/getMenuList")
    public RtnUtils getMenuList(){
        //通过上下文获取用户数据
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User principal = (User) authentication.getPrincipal();
        //获取当前用户的权限
        List<String> permissionList = principal.getPermissionList();


        return RtnUtils.ok();
    }



    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public RtnUtils logout(){
        return iLoginService.logout();
    }
}
